/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fyx.cms.web;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import org.fyx.cms.ejb.CmsLocal;
import org.fyx.cms.ejb.CmsRoles;
import org.fyx.cms.entity.CmsArticle;
import org.fyx.core.web.event.MenuCreatingEventHandler;
import org.fyx.core.web.event.RoleCreatingEventHandler;
import org.fyx.linker.web.LinkerLocal;
import org.fyx.mula.ejb.MulaLocal;
import org.fyx.secure.ejb.SecureLocal;
import org.fyx.secure.entity.SecureRole;
import org.primefaces.component.menuitem.MenuItem;

/**
 * Mula observer pro naslouchani na vnitrni udalosti.
 * Zoodpovida za spravne provedeni akci na urcite udalosti.
 * 
 * @author ydenek
 */
@Stateless
@LocalBean
public class CmsObserver implements Observer{

    @EJB
    private SecureLocal secure;
    @EJB
    private LinkerLocal linker;
    @EJB
    private MulaLocal mula;
    @EJB
    private CmsLocal cms;

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof MenuCreatingEventHandler) {
            menuCreate();
        } else if (o instanceof RoleCreatingEventHandler) {
            roleCreate();
        }
    }

    private void menuCreate() {
        MenuItem manageLanguage = new MenuItem();
        manageLanguage.setValue(mula.get("cms_articles"));  //musi byt stejne jako id
        manageLanguage.setIcon("ui-icon ui-icon-note");
        manageLanguage.setUrl(linker.getLink("cms/list.xhtml"));
        manageLanguage.setId("cms_articles");  //musi byt stejne jako value
        linker.addMenuItem(manageLanguage, CmsRoles.ARTICLES_MANAGER);
        
        List<CmsArticle> articles = cms.getArticles();
        for (CmsArticle cmsArticle : articles) {
            MenuItem item = new MenuItem();
            item.setValue(mula.get("cms_article_" + Integer.toString(cmsArticle.getId())));
            item.setIcon("ui-icon ui-icon-document");
            item.setUrl(linker.getLink("cms/show.xhtml?p1=" + Integer.toString(cmsArticle.getId())));
            item.setId("cms_article_" + Integer.toString(cmsArticle.getId()));
            linker.addMenuItem(item, CmsRoles.ARTICLES_READER);
        }
    }

    private void roleCreate() {
        SecureRole role = new SecureRole(CmsRoles.ARTICLES_MANAGER);
        role.setCategory("Content management");  //?
        role.setTitle("Article manager");  //?
        role.setDescription("Can manage articles."); //?
        secure.addRole(role);
        
        role = new SecureRole(CmsRoles.ARTICLES_READER);
        role.setCategory("Content management");  //?
        role.setTitle("Article reader");  //?
        role.setDescription("Can read articles."); //?
        secure.addRole(role);
    }
    
}
